# -*- coding:utf-8 -*-

from django.template import RequestContext
from django.http import HttpResponse,HttpResponseRedirect
from django.http import HttpResponseForbidden
from django.core.urlresolvers import reverse
from django.shortcuts import redirect,render, get_object_or_404
from django.contrib import auth, messages
from django.contrib.auth.models import User, Group
from django.views.decorators.csrf import csrf_exempt
from django.db.models import Count, Q
from disn.settings import YUNPIAN_APIKEY, PROJECT_PATH, BASE_DIR
from disn.settings import TOKEN, APPID, APPSECRET, ENCODING_AES_KEY
from disn.settings import JD_APP_KEY, JD_APP_SECRET
from disn.settings import get_wechat_client
from disn.settings import WECHAT_ADMIN_USER_ID
from disn.utilities import *
import random, requests, json, os, pdfkit, base64, re
from account.models import *
from django.core import serializers
from disn.share_post import *

# from weixin.models import *
from django.contrib.auth.decorators import login_required
from account.weixin import get_jssdk_signature
from django.core.paginator import Paginator
from taskqueue.tasks import *
from lxml import etree
from jd.client import JDClient

# import reportlab.lib.fonts
# from reportlab.lib.utils import ImageReader
# from reportlab.lib.pagesizes import letter, A4
# from reportlab.pdfgen.canvas import Canvas
# from reportlab.lib.units import inch, cm
# from io import BytesIO
# from reportlab.pdfbase import pdfmetrics
# from reportlab.pdfbase.cidfonts import UnicodeCIDFont
# from reportlab.pdfbase.ttfonts import TTFont
# font_path = '%s/disn/static/fonts/Yahei.ttf' %BASE_DIR
# pdfmetrics.registerFont(TTFont('Yahei', font_path))

# @login_required
# @csrf_exempt
# def m_youhui(request, mall=None, category=None):
#     page = int(request.GET.get('page', 1))
#     date_before_30_days = get_date_by_delta(datetime.datetime.today(), -30)
#     if mall:
#         items = Item.objects.filter(create_at__gte=date_before_30_days, active=True, article_mall__name=mall).order_by('-create_at')
#     else:
#         items = Item.objects.filter(create_at__gte=date_before_30_days, active=True).order_by('-create_at')
#     if category:
#         items = items.filter(top_category__name=category).order_by('-create_at')
#     items = items[:900]
#     p = Paginator(items, 30)
#     page_range = p.page_range
#     current_page_items = p.page(page)
#     is_ajax_req = request.GET.get('isAjax', None)
#     if is_ajax_req:
#         response_data = {}
#         results = [ob.as_json() for ob in current_page_items]
#         response_data['result'] = results
#         response_data['page'] = page
#         return HttpResponse(json.dumps(response_data), content_type="application/json")
#     else:
#         return render(request, 'm/youhui.html', {'category':category,'page':page, 'page_range':page_range, 'current_page_items': current_page_items})

# @login_required


@csrf_exempt
@login_required
def youhui(request, mall=None, category=None, channel=None):
    print('func youhui reload()')
    # print(mall,category)
    # category_list = Item.objects.filter(top_category__isnull=False).exclude(top_category__exact='').values('top_category').annotate(total=Count('top_category')).order_by('-total')
    # mall_list = Item.objects.filter(article_mall__isnull=False).exclude(article_mall__exact='').values('article_mall').annotate(total=Count('article_mall')).order_by('-total')
    wechat_from = request.GET.get('from', None)
    if wechat_from: #https://segmentfault.com/q/1010000002566983/a-1020000002567095
        if mall:
            return redirect('/youhui/mall/%s/' %mall)
        if category:
            return redirect('/youhui/category/%s/' %category)
        if channel:
            return redirect('/youhui/channel/%s/' %channel)
        else:
            return redirect('/youhui/')
    s = request.GET.get('s', None)
    page = int(request.GET.get('page', 1))
    if s:
        print('Search Keyword: %s' %s)
        source = request.GET.get('source', None)
        date_before_60_days = get_date_by_delta(datetime.datetime.today(), - 60)
        items = Item.objects.filter(create_at__gte=date_before_60_days, active=True, article_title__icontains=s).order_by('-create_at')
    else:
        date_before_30_days = get_date_by_delta(datetime.datetime.today(), - 30)
        category_list = Category.objects.filter(active=True).order_by('-order')
        mall_list = Mall.objects.filter(active=True).order_by('-order')
        if channel:
            items = Item.objects.filter(active=True, article_channel__pinyin=channel).order_by('-create_by')
        elif mall:
            items = Item.objects.filter(create_at__gte=date_before_30_days, active=True, article_mall__pinyin=mall).order_by('-create_at')
        elif category:
            items = Item.objects.filter(create_at__gte=date_before_30_days, active=True, top_category__pinyin=category).order_by('-create_at')
        else:
            items = Item.objects.filter(create_at__gte=date_before_30_days, active=True).order_by('-create_at')
    items = items[:1800]
    p = Paginator(items, 60)
    page_range = p.page_range
    current_page_items = p.page(page)
    is_ajax_req = request.GET.get('isAjax', None)
    if is_ajax_req:
        response_data = {}
        results = [ob.as_json() for ob in current_page_items]
        response_data['result'] = results
        response_data['page'] = page
        return HttpResponse(json.dumps(response_data), content_type="application/json")
    ua = request.META['HTTP_USER_AGENT'].lower()
    if request.user_agent.is_mobile or ua.find('micromessenger') >= 0:
        return render(request, 'zdm/youhui.html', {'category':category, 'category_name':Category.get_name_by_pinyin(category) ,'page':page, 'page_range':page_range, 'current_page_items': current_page_items, 'jssdk_signature':get_jssdk_signature(request)})
        # if request.user.is_staff or request.user.is_superuser:
        #     return render(request, 'zdm/youhui.html', {'category':category, 'category_name':Category.get_name_by_pinyin(category) ,'page':page, 'page_range':page_range, 'current_page_items': current_page_items, 'jssdk_signature':get_jssdk_signature(request)})
        # else:
        #     return render(request, 'm/youhui.html', {'category':category, 'category_name':Category.get_name_by_pinyin(category) ,'page':page, 'page_range':page_range, 'current_page_items': current_page_items, 'jssdk_signature':get_jssdk_signature(request)})
    else:
        return render(request, 'pc/youhui.html', {'mall_list':mall_list, 'category_list':category_list, 'page':page, 'page_range':page_range, 'current_page_items': current_page_items, 'jssdk_signature':get_jssdk_signature(request)})

@login_required
def detail(request, id):
    # display_request_meta(request)
    referrer = request.user.profile.id if request.user else '0'
    # wechat_from = request.GET.get('from', None)
    # if wechat_from: #https://segmentfault.com/q/1010000002566983/a-1020000002567095
        # return redirect('/youhui/detail/%s/' %id)
    is_redirect = request.GET.get('redirect', None)
    item = get_object_or_404(Item, Q(pk=id) | Q(article_id=id))
    # return render(request, 'm/detail.html', {'item': item, 'jssdk_signature':get_jssdk_signature(request)})
    ua = request.META['HTTP_USER_AGENT'].lower()
    promotion_url = None
    if ua.find('micromessenger') >= 0: # user from wechat
        if is_redirect:
            if item.commodity_url_refer_mb:
                promotion_url = item.commodity_url_refer_mb
            elif item.commodity_url_refer:
                promotion_url = item.commodity_url_refer
            else:
                promotion_url = item.commodity_url
            return redirect(promotion_url)
        else:
            return render(request, 'zdm/detail.html', {'referrer':referrer, 'category':item.top_category.pinyin, 'item': item, 'jssdk_signature':get_jssdk_signature(request)})
    else:
        if is_redirect:
            if item.commodity_url_refer:
                promotion_url = item.commodity_url_refer
            else:
                promotion_url = item.commodity_url
            return redirect(promotion_url)
        else:
            return render(request, 'zdm/detail.html', {'referrer':referrer, 'category':item.top_category.pinyin, 'item': item})

@login_required
def broadcast(request, id):
    if request.user.is_staff and request.user.is_superuser:
        wechat = get_wechat_client()
        item = get_object_or_404(Item, pk=id)
        all_user_profile = UserProfile.objects.filter(subscribed=True)
        for user_profile in all_user_profile:
            send_user_youhui.delay(wechat, user_profile, '优惠商品推荐', item, '点击购买', 'https://www.ztm.me/youhui/detail/%s/' % item.id)
        return HttpResponse('广播消息成功发送')
    else:
        return HttpResponse('仅限工作人员使用')

def callback(request):
    print ('function callback(request).')
    code  = request.GET.get('code',None)
    state = request.GET.get('state',None)
    return HttpResponse('%s\n%s' %(code,state))

@login_required
def jd_callback(request):
    print('function jd_callback reload.')
    print('='*80)
    for k,v in request.GET.items():
        print('%s=%s' %(k,v))
    print('='*80)
    if request.user.is_superuser and request.user.is_active:
        code  = request.GET.get('code',None)
        state = request.GET.get('state',None)
        redirect_url = 'https%3A%2F%2Fwww.ztm.me%2Fcps%2Fnaichajia%2Fcallback%2F'
        if code:
            return redirect('https://oauth.jd.com/oauth/token?grant_type=authorization_code&client_id=%s&redirect_uri=%s&code=%s&client_secret=%s' %(JD_APP_KEY, redirect_url, code, JD_APP_SECRET))
        else:
            return redirect('https://oauth.jd.com/oauth/authorize?response_type=code&client_id=%s&redirect_uri=%s' %(JD_APP_KEY, redirect_url))
    else:
        return HttpResponse('Access Denied!')

def get_jd_promotion_code(request):
    if request.method == 'POST':
        url = request.POST.get('url', 'https://www.jd.com')
        channel = request.POST.get('channel', 'PC')
        # print('url=%s\nchannel=%s' %(url, channel))
        jd = JDClient()
        ret_dict = jd.get_promotion_code(url, channel)
        # for k,v in ret_dict.items():
        #     print('%s=%s' %(k,v))
        return render(request, 'promotion.html', {'ret': ret_dict, 'url': url, 'channel': channel})
        # if ret_dict['code'] == '0':
        #     return HttpResponse('<h1><a href="%s" target="_blank">去JD购买</a></h1><h5>channel=PC|ML</h5><h5>url=https://www.jd.com</h5>' %ret_dict['url'])
        # else:
        #     return HttpResponse('%s<br/>%s' %(ret_dict['code'],ret_dict['msg']))
    else:
        return render(request, 'promotion.html')

@login_required
def manual_update_inactive(request):
    update_inactive.delay()
    return HttpResponse('update_inactive.delay() done.')

@login_required
def manual_delete_inactive(request):
    delete_inactive.delay()
    return HttpResponse('delete_inactive.delay() done.')

@login_required
def check_proxy(request):
    print_proxy.delay()
    return HttpResponse('print_proxy.delay() done.')

@login_required
def bind(request):
    if request.method == 'POST':
        mobile = request.POST.get('mobile',None)
        if mobile:
            new_username = 'tourist%s' %mobile
            current_user = request.user
            if not request.user.is_staff:
                current_user.username = new_username
                current_user.save()
            user_profile = current_user.profile
            user_profile.phone = mobile
            user_profile.mobile_verified = True
            user_profile.save()
            messages.add_message(request, messages.SUCCESS, '您的手机号码已完成验证!')
            # return render(request, "weui/bind.html", {'jssdk_signature':get_jssdk_signature(request)})
            return redirect('account.views.bind')
        else:
            messages.add_message(request, messages.ERROR, '请输入正确的手机号码','danger')
            return render(request, "weui/bind.html", {'jssdk_signature':get_jssdk_signature(request)} )
    else:
        return render(request, "weui/bind.html", {'jssdk_signature':get_jssdk_signature(request)})

@login_required
def dashboard(request):
    return render(request, 'account/dashboard.html', {'jssdk_signature':get_jssdk_signature(request)})

@login_required
def weixin_person_center(request):
    user = request.user
    user_profile = user.profile
    follower = UserProfile.objects.filter(subscribe_referrer=user).order_by('-subscribe_time')
    user_share_list = UserShare.objects.filter(owner=user, share_type='1').order_by('create_at')
    return render(request, 'weixin/person_center.html', {'user_profile':user_profile, 'follower':follower, 'user_share_list':user_share_list})

def logout(request):
    print('function logout(request) reload.')
    auth.logout(request)
    return redirect('/account/signin/')

def signin(request):
    print ('function signin(request) reload.')
    if request.method == 'POST':
        username = request.POST.get('username',None)
        password = request.POST.get('password',None)
        if username is None:
            messages.add_message(request, messages.ERROR, '请输入正确的用户名','danger')
        if password is None:
            messages.add_message(request, messages.ERROR, '请输入正确的密码','danger')
        if username is not None and password is not None:
            username = request.POST['username']
            password = request.POST['password']
            if '@' in username: # allowed email login
                try:
                    username = User.objects.get(email=username).username
                except User.DoesNotExist:
                    username = request.POST['username']
            user = auth.authenticate(username=username, password=s52d(password))
            if user is not None:
                if user.is_active:
                    auth.login(request, user)
                    messages.add_message(request, messages.SUCCESS, '恭喜您！登录成功！')
                    if True: # direct to account/dashboard.html during 评选活动期间
                        next_page_url = request.POST.get('next',None)
                        if next_page_url:
                            response = redirect(next_page_url)
                            return response
                        else:
                            response = redirect(reverse('account.views.dashboard'))
                            return response
                    else:
                        messages.add_message(request, messages.INFO, '请完善你的资料！或者您也可以暂不完善资料，直接<a href="/account/dashboard/">进入</a>')
                        response = redirect(reverse('account.views.editme'))
                        return response
                else:
                    messages.add_message(request, messages.ERROR, '账户被禁用，请联系管理员','danger')
            else:
                messages.add_message(request, messages.ERROR, '请输入正确的用户名密码','danger')
        return render(request, 'account/signin_mobile.html', {'jssdk_signature':get_jssdk_signature(request)})
    else:
        code = request.GET.get("code", None)
        print ('code=%s' %code)
        # referrer = request.GET.get('referrer','0')
        # print ('referrer=%s' %referrer)
        next_page_url = request.GET.get('next','/account/')
        print ('next_page_url=%s' %next_page_url)
        if code:
            oauth2_url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code' %(APPID, APPSECRET, code)
            print("Ready to access : %s" %oauth2_url)
            resp = requests.get(oauth2_url)
            # print('resp.content:\n%s' % resp.content)
            openid = json.loads(resp.content)['openid']
            user_profile = UserProfile.get_subscribed_user_by_openid(openid)
            next_page = request.GET.get('next',None)
            if user_profile:
                user = user_profile.user
                if user and user.is_active:
                    user.backend = 'django.contrib.auth.backends.ModelBackend'
                    auth.login(request,user)
                    if next_page:
                        print ('Next page is [%s]' %next_page)
                        return redirect(next_page)
                    else:
                        return redirect(reverse('account.views.dashboard'))
                else:
                    return HttpResponse('用户不存在或被禁用!')
            else:
                if next_page:
                    match_detail = re.match(r'/youhui/detail/(\d+)?/.*?=(\d+)?', next_page_url, re.M|re.I)
                    ua = request.META['HTTP_USER_AGENT'].lower()
                    if ua.find('micromessenger') >= 0 and next_page_url and match_detail:
                        item_id = match_detail.group(1)
                        referrer = match_detail.group(2)
                        print('item_id=%s,referrer=%s' %(item_id, referrer))
                        return render(request, 'account/signin_mobile.html',{'referrer':referrer, 'item_id': item_id, 'next':next_page_url, 'jssdk_signature':get_jssdk_signature(request)})
                    else:
                        return render(request, 'account/signin_mobile.html',{'next':next_page_url, 'jssdk_signature':get_jssdk_signature(request)})
                else:
                    return redirect('account.views.signin')
        else:
            return render(request, 'account/signin_mobile.html',{'next':next_page_url, 'jssdk_signature':get_jssdk_signature(request)})

def redirect_url(request, url):
    print (url)
    return HttpResponseRedirect(url)

def wx_redirect(request,next_page):
    print ('function wx_redirect reload, next_page=/%s' %next_page)
    next_url = '/%s' %next_page
    if request.user.is_authenticated():
        print ('user [%s] already logged in.' %request.user.username)
        return redirect(next_url)
    else:
        print ('ready to call wxredirect.html')
        return render(request, 'account/wxredirect.html', {'appid':APPID,'next_page':next_url, 'jssdk_signature':get_jssdk_signature(request)})


def sendsms(request):
    mobile = request.POST.get('mobile', None)
    try:
        user_by_mobile = UserProfile.objects.get(phone=mobile,mobile_verified=True)
    except UserProfile.DoesNotExist:
        user_by_mobile = None
    if user_by_mobile:
        result = {"count": 1, "code": 101, "mobile": mobile, "fee": 0.05, "msg": "此手机号码已经存在", "unit": "RMB"}
        return json.dumps(result, ensure_ascii=False) # 此手机号码已经存在
    code = str(random.randint(1000,9999))
    result = send_verfiy_code(mobile, code)
    return HttpResponse(result, content_type="application/json")

def send_verfiy_code(mobile, code):
    result = smsOperator.single_send({'mobile': mobile, 'text': '您的验证码是%s' %code})
    result_json = json.dumps(result.content, ensure_ascii=False)
    return result_json

# @login_required
def share_post_view(request):
    user_profile = None
    referrer = request.GET.get('referrer', None)
    if referrer:
        # 微信页右上角分享给好友或朋友圈
        try:
            user_profile = UserProfile.objects.get(id=int(referrer))
        except UserProfile.DoesNotExist:
            admin = get_or_create_admin()
            user_profile = admin.profile
    else:
        # 直接生成二维码分享
        if request.user.is_authenticated():
            user_profile = request.user.profile
        else:
            admin = get_or_create_admin()
            user_profile = admin.profile
    category = request.GET.get('category', None)
    qrcode_type = request.GET.get('qrcode_type', '0') # temporary=0, permanent=1
    item_id = request.GET.get('item_id', None)
    return create_share_post(item_id, user_profile, qrcode_type)

def create_share_post(item_id, user_profile, qrcode_type):
    if item_id:
        item = get_object_or_404(Item, pk=int(item_id))
        post_image = draw_item_post(user_profile=user_profile, qrcode_type=qrcode_type, item=item)
    else:
        post_image = draw_user_post(user_profile=user_profile, qrcode_type=qrcode_type)
    # Saving the image to the Django response object:
    if post_image:
        response = HttpResponse(content_type='image/png')
        post_image.save(response, 'PNG')
        return response
    else:
        return HttpResponse('https://img.ztm.me/img/noimg.png')


def help(request):
    return render(request, "weui/help.html", {'jssdk_signature':get_jssdk_signature(request)})

@login_required
def my_keywords(request):
    items_follow = UserVsKeyword.objects.filter(user=request.user.profile)
    return render(request, 'm/follow.html', {'items_follow': items_follow})

@csrf_exempt
@login_required
def post_keywords(request):
    response_data = {}
    if request.method == 'POST':
        print('='*80)
        for k,v in request.POST.items():
            print('%s=%s' %(k,v))
        print('='*80)
        method = request.POST.get('method', None)
        keyword = request.POST.get('keyword', None)
        include = request.POST.get('include', None)
        exclude = request.POST.get('exclude', None)
        expire_at = request.POST.get('expire_at', None)
        id = request.POST.get('id', None)
        if method == 'ADD':
            obj, created = Keyword.objects.get_or_create(name=keyword)
            user_keyword, user_keyword_created = UserVsKeyword.objects.get_or_create(keyword=obj, user=request.user.profile)
            print(user_keyword_created)
            if user_keyword_created:
                # user_keyword = UserVsKeyword()
                user_keyword.user = request.user.profile
                user_keyword.keyword = obj
                user_keyword.include = include
                user_keyword.exclude = exclude
                user_keyword.expire_at = expire_at
                user_keyword.save()
                obj.subscribe_times += 1
                obj.save()
                response_data['message'] = '关键字添加成功'
            else:
                response_data['message'] = '关键字已存在'
        elif method == 'EDIT':
            user_keyword = get_object_or_404(UserVsKeyword, pk=id)
            user_keyword.include = include
            user_keyword.exclude = exclude
            user_keyword.expire_at = expire_at
            user_keyword.save()
            user_keyword.save()
            response_data['message'] = '关键字修改成功'
        elif method == 'DELETE':
            print('delete[%s]' %id)
            user_keyword = get_object_or_404(UserVsKeyword, pk=id)
            obj = user_keyword.keyword
            user_keyword.delete()
            obj.subscribe_times -= 1
            obj.save()
            response_data['message'] = '关键字删除成功'
        elif method == 'TOGGLE':
            user_keyword = get_object_or_404(UserVsKeyword, pk=id)
            user_keyword.active = not user_keyword.active
            user_keyword.save()
            if user_keyword.active:
                response_data['message'] = '关键字已启用'
            else:
                response_data['message'] = '关键字已禁用'
        response_data['status'] = 'SUCCESS'
        return HttpResponse(json.dumps(response_data), content_type="application/json")
    else:
        response_data['status'] = 'FAIL'
        response_data['message'] = '请使用POST请求'
        return HttpResponse(json.dumps(response_data), content_type="application/json")

@login_required
def crawl_sina_stars(request):
    header = {'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.9; rv:32.0) Gecko/20100101 Firefox/32.0',}
    s = requests.Session()
    rex_replace = re.compile('<span class="txt">.*?:</span>')
    for page in range(100): # 1846
        url = 'http://ku.ent.sina.com.cn/star?page_no=%d' %(page+1)
        resp = s.get(url, headers=header)
        raw_html = rex_replace.sub(r'', resp.text)
        root = etree.HTML(raw_html)
        results = root.xpath('//div[@class="module-box"]')
        result = results[0]
        li_list = result.xpath('./ul/li')
        for li in li_list:
            try:
                name = li.xpath('./div/div/h4/a/text()')[0]
            except Exception as e:
                print('Exception: name not found', end)
                print(e, ':Name not found.')
                continue
            try:
                score = li.xpath('./div/div/span/text()')[0]
            except Exception as e:
                print(e, ':Score not found')
                continue
            try:
                constellation = li.xpath('./div/p/a/text()')[-1]
            except Exception as e:
                print(e, ':Constellation not found')
                continue
            try:
                gender = li.xpath('./div/p/text()')[0]
            except Exception as e:
                gender = None
                print(e)
            try:
                photo = li.xpath('./a/img/@src')[0]
            except Exception as e:
                print(e)
                continue
            try:
                birth_date = datetime.datetime.strptime((li.xpath('./div/p[@class="special"]/text()')[0]).strip(), "%Y-%m-%d")
            except Exception as e:
                birth_date = None
                print(e)
            star, created = Star.objects.get_or_create(name=name, score=score,constellation=constellation)
            if created:
                star.name = name
                star.score = score
                star.gender = gender
                star.birth_date = birth_date
                star.constellation = constellation
                star.photo = photo
                star.save()
    return HttpResponse('Done')
